package noblob;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Movie;
import model.PMF;

public class ShowImage extends HttpServlet {

	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		showImage(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		showImage(req, resp);
	}
	
	private void showImage(HttpServletRequest req, HttpServletResponse resp){
		
//		byte[] imgStream= ProvaUploadNOblobServlet.img;
		
		
		//Inizio recupero immagine dal datastore
		String title = req.getParameter("title");
		Movie movie = getMovie(title);
		
		
		if (movie != null && movie.getImageType() != null &&
                movie.getImage() != null) {
            // Set the appropriate Content-Type header and write the raw bytes
            // to the response's output stream
            resp.setContentType(movie.getImageType());
            try {
				resp.getOutputStream().write(movie.getImage());
				resp.getOutputStream().flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        } else {
            // If no image is found with the given title, redirect the user to
            // a static image
           
        }
	}

	/**
	 * Queries the datastore for the Movie object with the passed-in title. If
	 * found, returns the Movie object; otherwise, returns null.
	 *
	 * @param title movie title to look up
	 */
	private Movie getMovie(String title) {
	    PersistenceManager pm = PMF.get().getPersistenceManager();

	    // Search for any Movie object with the passed-in title; limit the number
	    // of results returned to 1 since there should be at most one movie with
	    // a given title
	    Query query = pm.newQuery(Movie.class, "title == titleParam");
	    query.declareParameters("String titleParam");
	    query.setRange(0, 1);

	    try {
	        List<Movie> results = (List<Movie>) query.execute(title);
	        if (results.iterator().hasNext()) {
	            // If the results list is non-empty, return the first (and only)
	            // result
	            return results.get(0);
	        }
	    } finally {
	        query.closeAll();
	        pm.close();
	    }

	    return null;
	}
}
